package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ProduceConsume {
    public static final int MAX_COUNT = 10;
    public  boolean flag = true;
    private List<Integer> pool = new ArrayList<>();
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public void produce(){
        new Thread(()->{
            while (flag) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (this) {
                    while (pool.size() >= 10) {//注意：这里要用while判断，不能用if，用if多个生产者被notify，只判断一次就会出现大于10的情况、
                        try {
                            System.out.println("pool is full,waiting");
                           this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Integer pro = atomicInteger.incrementAndGet();
                    pool.add(pro);
                    System.out.println("生产商品" + pro +",库存=" + pool );
                    this.notifyAll();
                }
            }
        }).start();

    }

    public void consume(){
        new Thread(()->{
            while (flag) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (this) {
                    while (pool.size() <= 0) {
                        try {
                            System.out.println("pool is empty,waiting");
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int temp = pool.get(0);
                    pool.remove(0);
                    System.out.println("消费商品" + temp  +",库存=" + pool);
                }
            }
        }).start();
    }

    public void stop(){
        flag=false;
    }

    public static void main(String[] args) throws InterruptedException {
        ProduceConsume p = new ProduceConsume();
        p.consume();
        p.produce();
        p.produce();
        Thread.sleep(2000);
        p.stop();
    }


}
